<?php

namespace App\Service;

use App\Common\Ai\XFYunApi;
use App\Common\Logs\Logs;
use App\Common\Utill\OperationLog;
use App\Common\Utill\Utills;
use App\Http\Controllers\Common\UploadsController;
use App\Models\Articles;
use App\Models\Category;
use App\Models\Websites;
use App\Models\WebsitesAdmin;
use App\Models\WebsitesTopic;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Parsedown;

class ArticlesService extends CommonService
{
    public function __construct()
    {
        parent::__construct();
    }
    /**
     * 列表数据
     * @param $request
     * @param $num
     * @return array|mixed
     */
    public function getListData($request, $num)
    {
        //$this->setArticleCategoryId();
        $model = new Articles();
        $query = $model::query();
        $query->from("pd_articles as a");
        //标题
        $title = $request->input('title', '');
        if ($title) {
            $query->where('a.title', 'like', '%' . $title . '%');
        }
        //状态
        $status = $request->input('status', '');
        if ($status != '') {
            $query->where('a.status', $status);
        }
        //时间筛选
        $add_time = $request->input('add_time', '');
        if ($add_time) {
            $timeArr = explode(' - ', $add_time);
            $start_time = $timeArr[0];
            $end_time = $timeArr[1];
            $query->whereBetween('a.created_at', [$start_time, $end_time]);
        }
        $accountAuthType = self::accountAuthType();
        //网站地址
        $website_id = $request->input('website_id', 0);
        if ($website_id) {
            $query->where('a.website_id', $website_id);
        }else{
            if($accountAuthType != 1){
                $websiteArr = WebsitesAdminService::getAdminWebsites();
                if($websiteArr){
                    $query->whereIn('a.website_id', $websiteArr);
                }else{
                    $query->where('a.website_id', -1);
                }
            }
        }
        //栏目
        $topicId = $request->input('websites_topic_id', 0);
        if ($topicId) {
            $query->where('a.websites_topic_id', $topicId);
        }
        //关键词
        $categoryId = $request->input('category_id', 0);
        if ($categoryId) {
            $query->where('a.category_id', $categoryId);
        }
        //获取网站地址
        $getWebsiteData = WebsitesService::getWebsiteData(2,1);
        $query->where("a.is_del", 1);
        $query->orderBy('a.id', 'desc');
        $query->leftJoin("pd_category as c","c.id","=","a.category_id");
        $query->leftJoin("pd_websites_topic as t","t.id","=","a.websites_topic_id");
        $query->select("a.*","c.category_name","t.titles as topic_name");
        $result = $query->paginate($num)->toArray();
        foreach ($result['data'] as $key => $val) {
            $result['data'][$key]['content'] = strip_tags($val['content']);
            $result['data'][$key]['statusName'] = $this->statusName($val['status']);
            $result['data'][$key]['websiteName'] = $getWebsiteData[$val['website_id']] ?? '';
        }
        return $this->success('SUCCESS', $result['total'], $result['data']);
    }

    public function statusName($status)
    {
        $arr = [-1 => '已下架', 0 => '审核中', 1 => '已拒绝', 2 => '已发布'];
        return $arr[$status];
    }

    /**
     * 文章保存
     * @param $category_ids  //关键词
     * @param $website_id  //网站id
     * @param $title   //标题
     * @param $content //内容
     * @param $thumbs   //缩略图
     * @param $fromSource //来源 1=后台 2=脚本生成
     * @param $topic_id //栏目id
     * @return array|mixed
     */
    public function store($category_ids, $website_id, $topic_id,$title, $content,$thumbs='',$fromSource=1)
    {
        if($fromSource == 1){
            $operationData = self::operationData($website_id);
            $adminId     = $operationData['admin_id'];
            $operationId = $operationData['operation_id'];
        }else{
            $adminId = WebsitesAdmin::query()->where('website_id',$website_id)->value('admin_id') ?? 1;
            $operationId = $adminId;
        }
        $category_id = rtrim($category_ids, ',');
        //数据入库
        $postData['admin_id'] = $adminId;
        $postData['website_id'] = $website_id;
        $postData['websites_topic_id'] = $topic_id;
        $postData['category_id'] = $category_id;
        $postData['title'] = $title;
        $postData['content'] = $content;
        $postData['thumbs'] = $thumbs;
        $postData['status'] = 2;
        $postData['publish_time'] = date('Y-m-d H:i:s');
        $postData['created_at'] = date('Y-m-d H:i:s');
        $postData['updated_at'] = date('Y-m-d H:i:s');
        $postData['from_source'] = $fromSource;
        $postData['operation_id'] = $operationId;
        $resId = DB::table("pd_articles")->insertGetId($postData);
        if (!$resId) {
            return $this->error('添加失败');
        }
        //计算次数
        Category::query()->where('id',$category_id)->increment('use_numbers');
        WebsitesTopic::query()->where('id',$topic_id)->increment('article_count');
        if($fromSource == 2){
            return  $resId;
        }
        OperationLog::record(1,'文章管理-添加',$resId,$postData);
        return $this->success('添加成功');
    }

    /**
     * 更新数据
     * @return void
     */
    public function update($id, $title, $content, $status,$website_id,$websites_topic_id,$thumbs)
    {
        $oldData = Articles::query()->where('id', $id)->first()->toArray();
        $postData['title'] = $title;
        $postData['content'] = $content;
        $postData['status'] = $status;
        $postData['website_id'] = $website_id;
        $postData['websites_topic_id'] = $websites_topic_id;
        $postData['thumbs'] = $thumbs;
        if ($status == 2) {
            $postData['publish_time'] = date('Y-m-d H:i:s');
        }
        $res = Articles::query()->where('id', $id)->update($postData);
        if (!$res) {
            return $this->error("更新失败");
        }
        OperationLog::record(2,'文章管理-编辑',$id,$postData,$oldData);
        return $this->success("更新成功");
    }

    /**
     * 生成ai标题/内容
     * @param $request
     * @return void
     */
    public function ai_content($request)
    {
        $type = $request->input('type', 1);
        $categoryIds = $request->input('category_ids', '');
        $categoryIds = trim($categoryIds, ',');
        if (!$categoryIds && $type == 1) {
            return $this->error('关键词不能为空');
        }
        //获取分类名称
        if($type == 1){
            $categoryName = $this->getCategoryNameById($categoryIds);
        }else{
            $categoryName = $request->input('title', '');
        }

        //生成唯一的编码
        $orderSn = Utills::aiOrderSn();

        $xfYunApi = new XFYunApi();
        if ($type == 1) {//标题
            $aiInstruction = $this->getTitleText($categoryName);
            $aiResult = $xfYunApi->sendRequest($orderSn, $aiInstruction);
        } else {//内容
            $aiInstruction = $this->getContentText($categoryName);
            $aiResult = $xfYunApi->sendRequest($orderSn, $aiInstruction, 2);
        }
        $returnContent = $this->articlesTokenRecord($type, $orderSn, $aiInstruction, $aiResult);
        $resul['return_content'] = $returnContent['content'];
        return $this->success('SUCCESS', 1, $resul);
    }

    /**
     * 入库
     * @param $type  //1=标题 2=内容
     * @param $orderSn //订单号
     * @param $describe //描述
     * @param $result //返回结果
     * @param $source //来源 1=后台添加 2=自动脚本
     * @return mixed|string|null
     */
    public function articlesTokenRecord($type, $orderSn, $describe, $result,$source=1,$taskSn='')
    {
        $returnContent = "";
        $returnThumbs  = '';
        if ($type == 1) {//标题
            if ($result['message'] == 'Success') {
                $content = trim($result['content'], "```json \n");
                $answer = json_decode($content, true);
                if(isset($answer['title'])){
                    $returnContent = $answer['title'];
                }elseif(isset($answer[0]['title'])){
                    $returnContent = $answer[0]['title'];
                }else{
                    $returnContent = $answer[0];
                }
            }
        } else {
            if ($result['message'] == 'Success') {
                $parsedown = new Parsedown();
                $returnContent = $parsedown->text($result['content']);
                $newContent = $this->contentImages($returnContent,$taskSn);
                $returnContent = $newContent['content'];
                $returnThumbs  = $newContent['thumbs'];
            }
        }
        $postData = array();
        $postData['order_sn'] = $orderSn;
        $postData['type'] = $type;
        $postData['describe'] = $describe;
        $postData['content'] = $returnContent;
        $postData['total_token'] = $result['totalTokens'];
        $postData['created_at'] = date('Y-m-d H:i:s');
        $postData['return_content'] = json_encode($result['return_content'], JSON_UNESCAPED_UNICODE);
        $postData['source'] = $source;
        $postData['taskSn'] = $taskSn;
        DB::table("pd_articles_token_record")->insert($postData);
        $returnData['content'] = $returnContent;
        $returnData['thumbs'] = $returnThumbs;
        return $returnData;
    }

    /**
     * ai生成标题文字描述
     * @param $categoryName //关键词
     * @return void
     */
    public function getTitleText($categoryName)
    {
        $aiInstruction = "按照下面的描述,生成1个标题，标题中含有" . $categoryName . "等关键词，标题中不要含有特殊符号，标题的长度15-25个字之间,返回json格式一维数组。";
        return $aiInstruction;
    }

    /**
     * ai生成文章内容
     * @return void
     */
    public function getContentText($categoryName)
    {
        $aiInstruction = "按照下面的描述,写一篇文章内容。字数要求：800-1000个字,不要文章的标题,内容方向: " . $categoryName;
        return $aiInstruction;
    }

    /**
     * 获取分类的名称
     * @param $ids
     * @return string
     */
    public function getCategoryNameById($ids)
    {
        $result = "";
        $ids = explode(',', $ids);
        $categoryName = Category::query()->whereIn("id", $ids)->select("id", "category_name")->get()->toArray();
        foreach ($categoryName as $k => $v) {
            $result .= $v['category_name'] . ",";
        }
        $result = rtrim($result, ",");
        return $result;
    }

    /**
     * 释放
     */
    public function release($id)
    {
        $result = Articles::findOrFail($id);
        $result->website_id = 0;
        $result->websites_topic_id = 0;
        $result->operation_id = $this->adminId;
        $result->updated_at = date("Y-m-d H:i:s");
        if (!$result->save()) {
            return $this->error('操作失败');
        }
        OperationLog::record(6,'文章管理-释放',$id);
        return $this->success("操作成功");
    }

    /**
     * 单个删除
     */
    public function delOne($id)
    {
        $result = Articles::findOrFail($id);
        $result->is_del = -1;
        $result->deleted_at = date("Y-m-d H:i:s");
        if (!$result->save()) {
            return $this->error('删除失败');
        }
        OperationLog::record(3,'文章管理-删除',$id);
        return $this->success("删除成功");
    }

    /**
     * 批量删除
     * @return void
     */
    public function delAll($idArr)
    {
        if (!$idArr) {
            return $this->error('删除内容不能为空');
        }
        Log::info("删除id:", $idArr);
        $delData['is_del'] = -1;
        $delData['deleted_at'] = date("Y-m-d H:i:s");
        $result = Articles::whereIn("id", $idArr)->update($delData);
        if (!$result) {
            return $this->error('删除失败');
        }
        OperationLog::record(3,'文章管理-删除',0,'','',implode(",", $idArr));
        return $this->success("删除成功");
    }

    /**
     * 获取所有的七牛云图片入库
     * @return void
     */
    public function thumbs()
    {
        $uploads = new UploadsController();
        $uploads->listFiles();
    }

    /**
     * 文章里面随机插入图片
     * @param $content
     * @return void
     */
    public function contentImages($content,$taskSn)
    {
        $count = substr_count($content, '</p>');
        $getimgs='';
        if ($count) {
            //获取图片信息
            $imagesArrNew = [];
            $imagesArr = DB::table("pd_ai_images")->select("id","thumbs")->where("is_del",1)->orderBy("id","desc")->limit(1000)->get()->toArray();
            foreach ($imagesArr as $kk=>$vv){
                $imagesArrNew[$vv->id] = $vv->thumbs;
            }
            //获取下标
            $imagesKeyArr = array_keys($imagesArrNew);
            shuffle($imagesKeyArr);
            //获取图片地址
            $num1  = $imagesKeyArr[0];
            $num2  = $imagesKeyArr[1];
            $getimgs =  $imagesArrNew[$num1];
            $getimgss = $imagesArrNew[$num2];
            $j = 0;//</p>重新定位用的
            $numone = 1;
            $numtwo = -1;
            if ($count == 2) {
                $numtwo = 2;
            } elseif ($count > 2) {
                $numtwo = rand(2, $count - 1);
            }
            //Logs::info("num1:".$numone.",num2:".$numtwo);
            $addPositionNum = 1;
            for ($i = 1; $i <= $count; $i++) {
                $j = strpos($content, '</p>', $j);
                if ($i == $numone) {
                    //Log::info("内容追加图片step-1 j:".$j.",前内容:".substr($content, 0, $j));
                    $firstChaContent = '<div class="add_images"><img src="' . $getimgs . '" /></div>';
                    $addPositionNum = mb_strlen($firstChaContent, 'utf-8') + 20;
                    $content = substr($content, 0, $j) .$firstChaContent . substr($content, $j);
                } elseif ($i == $numtwo) {
                   //Log::info("内容追加图片step-2 j:".$j.",前内容:".substr($content, 0, $j));
                    $content = substr($content, 0, $j) . ('<div class="add_images"><img src="' . $getimgss . '" /></div>') . substr($content, $j);
                }
                $j = ($j + $addPositionNum);
            }
            Logs::crontabLog("任务编号-{$taskSn} 生成图片: num1:{$numone},num2:{$numtwo},id-1:{$num1},id-2:{$num2}".$content,[],'task');
            //图片使用次数统计
            DB::table("pd_ai_images")->where('id',$num1)->increment('use_numbers');
            DB::table("pd_ai_images")->where('id',$num2)->increment('use_numbers');
            //echo $content;
        }
        $result['content'] = $content;
        $result['thumbs']  = $getimgs;
        return $result;
    }

    public function setArticleCategoryId()
    {
        $data = DB::table("pd_articel_category")
            ->select('articles_id','category_id')
            ->groupBy('articles_id')
            ->get()
            ->toArray();
        foreach ($data as $kk=>$val){
            DB::table('pd_articles')->where('id',$val->articles_id)->update(['category_id'=>$val->category_id]);
        }
    }
}
